<template>
  <div class="documents-container">
    <div class="documents-header">
      <h1>文档管理</h1>
      <div class="header-actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索文档"
          prefix-icon="el-icon-search"
          clearable
          @clear="handleSearchClear"
          style="width: 250px; margin-right: 15px;"
        />
        <el-button type="primary" @click="showUploadDialog">上传文档</el-button>
        <el-button type="success" @click="showCreateFolderDialog">新建文件夹</el-button>
      </div>
    </div>

    <div class="documents-filters">
      <el-select v-model="filterProject" placeholder="项目筛选" clearable style="width: 180px; margin-right: 15px;">
        <el-option
          v-for="project in projects"
          :key="project.id"
          :label="project.name"
          :value="project.id"
        />
      </el-select>
      <el-select v-model="filterType" placeholder="文档类型" clearable style="width: 150px; margin-right: 15px;">
        <el-option label="全部" value="" />
        <el-option label="文件夹" value="folder" />
        <el-option label="文档" value="document" />
        <el-option label="图片" value="image" />
        <el-option label="视频" value="video" />
        <el-option label="其他" value="other" />
      </el-select>
    </div>

    <div class="breadcrumb-container">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/documents' }">文档根目录</el-breadcrumb-item>
        <el-breadcrumb-item 
          v-for="(folder, index) in currentPath" 
          :key="index"
          :to="{ path: `/documents?path=${getPathUpTo(index)}` }"
        >
          {{ folder.name }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-table
      v-loading="loading"
      :data="filteredDocuments"
      style="width: 100%"
      @row-click="handleRowClick"
      @row-contextmenu="handleContextMenu"
    >
      <el-table-column label="名称" min-width="300">
        <template #default="scope">
          <div class="document-name">
            <el-icon v-if="scope.row.type === 'folder'" class="document-icon folder-icon">
              <i class="el-icon-folder"></i>
            </el-icon>
            <el-icon v-else-if="isImageFile(scope.row.name)" class="document-icon image-icon">
              <i class="el-icon-picture"></i>
            </el-icon>
            <el-icon v-else-if="isVideoFile(scope.row.name)" class="document-icon video-icon">
              <i class="el-icon-video-camera"></i>
            </el-icon>
            <el-icon v-else class="document-icon document-icon">
              <i class="el-icon-document"></i>
            </el-icon>
            <span>{{ scope.row.name }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="project_name" label="所属项目" min-width="150" show-overflow-tooltip />
      <el-table-column prop="size" label="大小" width="120">
        <template #default="scope">
          <span v-if="scope.row.type !== 'folder'">{{ formatFileSize(scope.row.size) }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="created_by" label="创建者" width="120" />
      <el-table-column prop="created_at" label="创建时间" width="180" />
      <el-table-column prop="updated_at" label="更新时间" width="180" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button 
            v-if="scope.row.type !== 'folder'" 
            size="small" 
            @click.stop="downloadDocument(scope.row)"
          >
            下载
          </el-button>
          <el-button 
            v-if="scope.row.type !== 'folder'" 
            size="small" 
            type="primary" 
            @click.stop="previewDocument(scope.row)"
          >
            预览
          </el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click.stop="deleteDocument(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-if="totalDocuments > pageSize"
      class="pagination"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="totalDocuments"
      layout="total, prev, pager, next, jumper"
      @current-change="handlePageChange"
    />

    <!-- 上传文档对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传文档"
      width="500px"
    >
      <el-form :model="uploadForm" :rules="uploadRules" ref="uploadFormRef" label-width="100px">
        <el-form-item label="所属项目" prop="project_id">
          <el-select v-model="uploadForm.project_id" placeholder="请选择项目" style="width: 100%">
            <el-option
              v-for="project in projects"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文档描述" prop="description">
          <el-input v-model="uploadForm.description" type="textarea" placeholder="请输入文档描述" />
        </el-form-item>
        <el-form-item label="文档文件" prop="file">
          <el-upload
            class="upload-demo"
            drag
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :limit="1"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">拖拽文件到此处，或<em>点击上传</em></div>
            <template #tip>
              <div class="el-upload__tip">支持任意类型文件，大小不超过50MB</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUpload">上传</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新建文件夹对话框 -->
    <el-dialog
      v-model="createFolderDialogVisible"
      title="新建文件夹"
      width="500px"
    >
      <el-form :model="folderForm" :rules="folderRules" ref="folderFormRef" label-width="100px">
        <el-form-item label="文件夹名称" prop="name">
          <el-input v-model="folderForm.name" placeholder="请输入文件夹名称" />
        </el-form-item>
        <el-form-item label="所属项目" prop="project_id">
          <el-select v-model="folderForm.project_id" placeholder="请选择项目" style="width: 100%">
            <el-option
              v-for="project in projects"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="folderForm.description" type="textarea" placeholder="请输入文件夹描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createFolderDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCreateFolder">创建</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 文档预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      :title="previewDocument ? previewDocument.name : '文档预览'"
      width="80%"
      top="5vh"
      fullscreen
    >
      <div v-if="previewDocument" class="preview-container">
        <div v-if="isImageFile(previewDocument.name)" class="image-preview">
          <img :src="previewDocument.url || 'https://via.placeholder.com/800x600'" alt="文档预览" />
        </div>
        <div v-else-if="isVideoFile(previewDocument.name)" class="video-preview">
          <video controls>
            <source :src="previewDocument.url" :type="getVideoType(previewDocument.name)">
            您的浏览器不支持视频播放
          </video>
        </div>
        <div v-else-if="isPdfFile(previewDocument.name)" class="pdf-preview">
          <iframe :src="previewDocument.url || 'about:blank'" width="100%" height="600"></iframe>
        </div>
        <div v-else class="document-preview">
          <p>该文件类型不支持在线预览，请下载后查看</p>
          <el-button type="primary" @click="downloadDocument(previewDocument)">下载文件</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 右键菜单 -->
    <div v-show="contextMenuVisible" :style="contextMenuStyle" class="context-menu">
      <ul>
        <li v-if="selectedDocument && selectedDocument.type === 'folder'" @click="openFolder(selectedDocument)">
          <i class="el-icon-folder-opened"></i> 打开文件夹
        </li>
        <li v-if="selectedDocument && selectedDocument.type !== 'folder'" @click="showPreviewDocument(selectedDocument)">
          <i class="el-icon-view"></i> 预览
        </li>
        <li v-if="selectedDocument && selectedDocument.type !== 'folder'" @click="downloadDocument(selectedDocument)">
          <i class="el-icon-download"></i> 下载
        </li>
        <li v-if="selectedDocument" @click="renameDocument(selectedDocument)">
          <i class="el-icon-edit"></i> 重命名
        </li>
        <li v-if="selectedDocument" @click="deleteDocument(selectedDocument)">
          <i class="el-icon-delete"></i> 删除
        </li>
        <li v-if="selectedDocument" @click="showDocumentProperties(selectedDocument)">
          <i class="el-icon-info"></i> 属性
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'
// import { useStore } from 'vuex'
// import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'DocumentsView',
  setup() {
    // const store = useStore()
    // const router = useRouter()
    // const route = useRoute()
    
    const loading = ref(true)
    const searchQuery = ref('')
    const filterProject = ref('')
    const filterType = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    
    const uploadDialogVisible = ref(false)
    const createFolderDialogVisible = ref(false)
    const previewDialogVisible = ref(false)
    const previewDocument = ref(null)
    
    const uploadFormRef = ref(null)
    const folderFormRef = ref(null)
    
    // 右键菜单相关
    const contextMenuVisible = ref(false)
    const contextMenuStyle = ref({
      top: '0px',
      left: '0px'
    })
    const selectedDocument = ref(null)
    
    // 当前路径
    const currentPath = ref([])
    
    // 上传表单
    const uploadForm = reactive({
      project_id: '',
      description: '',
      file: null
    })
    
    // 上传表单验证规则
    const uploadRules = {
      project_id: [
        { required: true, message: '请选择所属项目', trigger: 'change' }
      ],
      file: [
        { required: true, message: '请选择要上传的文件', trigger: 'change' }
      ]
    }
    
    // 文件夹表单
    const folderForm = reactive({
      name: '',
      project_id: '',
      description: ''
    })
    
    // 文件夹表单验证规则
    const folderRules = {
      name: [
        { required: true, message: '请输入文件夹名称', trigger: 'blur' },
        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
      ],
      project_id: [
        { required: true, message: '请选择所属项目', trigger: 'change' }
      ]
    }
    
    // 模拟项目数据
    const projects = ref([
      {
        id: 1,
        name: '企业官网重构项目'
      },
      {
        id: 2,
        name: '移动应用开发'
      },
      {
        id: 3,
        name: '数据分析平台'
      }
    ])
    
    // 模拟文档数据
    const documents = ref([
      {
        id: 1,
        name: '项目需求文档',
        type: 'document',
        extension: 'docx',
        size: 2500000,
        project_id: 1,
        project_name: '企业官网重构项目',
        path: '/',
        created_by: '张三',
        created_at: '2023-01-15 10:30',
        updated_at: '2023-01-15 10:30',
        url: 'https://example.com/documents/1.docx'
      },
      {
        id: 2,
        name: '系统架构设计',
        type: 'document',
        extension: 'pdf',
        size: 5000000,
        project_id: 1,
        project_name: '企业官网重构项目',
        path: '/',
        created_by: '李四',
        created_at: '2023-01-20 14:15',
        updated_at: '2023-01-25 09:45',
        url: 'https://example.com/documents/2.pdf'
      },
      {
        id: 3,
        name: '设计资源',
        type: 'folder',
        project_id: 1,
        project_name: '企业官网重构项目',
        path: '/',
        created_by: '王五',
        created_at: '2023-01-22 11:20',
        updated_at: '2023-01-22 11:20'
      },
      {
        id: 4,
        name: '项目计划',
        type: 'document',
        extension: 'xlsx',
        size: 1800000,
        project_id: 1,
        project_name: '企业官网重构项目',
        path: '/',
        created_by: '张三',
        created_at: '2023-01-25 16:40',
        updated_at: '2023-02-10 14:30',
        url: 'https://example.com/documents/4.xlsx'
      },
      {
        id: 5,
        name: '首页设计稿',
        type: 'image',
        extension: 'png',
        size: 3500000,
        project_id: 1,
        project_name: '企业官网重构项目',
        path: '/设计资源',
        created_by: '王五',
        created_at: '2023-01-28 09:15',
        updated_at: '2023-01-28 09:15',
        url: 'https://example.com/documents/5.png'
      },
      {
        id: 6,
        name: '产品页设计稿',
        type: 'image',
        extension: 'png',
        size: 4200000,
        project_id: 1,
        project_name: '企业官网重构项目',
        path: '/设计资源',
        created_by: '王五',
        created_at: '2023-01-30 11:25',
        updated_at: '2023-01-30 11:25',
        url: 'https://example.com/documents/6.png'
      },
      {
        id: 7,
        name: '需求调研报告',
        type: 'document',
        extension: 'pdf',
        size: 3800000,
        project_id: 2,
        project_name: '移动应用开发',
        path: '/',
        created_by: '赵六',
        created_at: '2023-02-05 15:10',
        updated_at: '2023-02-05 15:10',
        url: 'https://example.com/documents/7.pdf'
      },
      {
        id: 8,
        name: 'UI设计规范',
        type: 'document',
        extension: 'pdf',
        size: 2900000,
        project_id: 2,
        project_name: '移动应用开发',
        path: '/',
        created_by: '王五',
        created_at: '2023-02-10 10:45',
        updated_at: '2023-02-10 10:45',
        url: 'https://example.com/documents/8.pdf'
      },
      {
        id: 9,
        name: '产品演示视频',
        type: 'video',
        extension: 'mp4',
        size: 25000000,
        project_id: 2,
        project_name: '移动应用开发',
        path: '/',
        created_by: '张三',
        created_at: '2023-02-15 16:30',
        updated_at: '2023-02-15 16:30',
        url: 'https://example.com/documents/9.mp4'
      },
      {
        id: 10,
        name: '数据库设计文档',
        type: 'document',
        extension: 'pdf',
        size: 4500000,
        project_id: 3,
        project_name: '数据分析平台',
        path: '/',
        created_by: '李四',
        created_at: '2023-01-10 09:20',
        updated_at: '2023-01-15 14:35',
        url: 'https://example.com/documents/10.pdf'
      }
    ])
    
    // 筛选后的文档列表
    const filteredDocuments = computed(() => {
      let result = documents.value
      
      // 路径过滤
      const currentPathStr = currentPath.value.map(folder => folder.name).join('/')
      const path = currentPathStr ? `/${currentPathStr}` : '/'
      result = result.filter(doc => doc.path === path)
      
      // 搜索过滤
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        result = result.filter(doc => 
          doc.name.toLowerCase().includes(query) ||
          (doc.description && doc.description.toLowerCase().includes(query))
        )
      }
      
      // 项目过滤
      if (filterProject.value) {
        result = result.filter(doc => doc.project_id === filterProject.value)
      }
      
      // 类型过滤
      if (filterType.value) {
        result = result.filter(doc => doc.type === filterType.value)
      }
      
      // 分页
      const startIndex = (currentPage.value - 1) * pageSize.value
      return result.slice(startIndex, startIndex + pageSize.value)
    })
    
    // 总文档数
    const totalDocuments = computed(() => {
      let result = documents.value
      
      // 路径过滤
      const currentPathStr = currentPath.value.map(folder => folder.name).join('/')
      const path = currentPathStr ? `/${currentPathStr}` : '/'
      result = result.filter(doc => doc.path === path)
      
      // 搜索过滤
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        result = result.filter(doc => 
          doc.name.toLowerCase().includes(query) ||
          (doc.description && doc.description.toLowerCase().includes(query))
        )
      }
      
      // 项目过滤
      if (filterProject.value) {
        result = result.filter(doc => doc.project_id === filterProject.value)
      }
      
      // 类型过滤
      if (filterType.value) {
        result = result.filter(doc => doc.type === filterType.value)
      }
      
      return result.length
    })
    
    // 获取文档列表
    const fetchDocuments = async () => {
      loading.value = true
      try {
        // 实际项目中应该从API获取数据
        // const response = await store.dispatch('document/getDocuments')
        // documents.value = response.data
        
        // 模拟API请求延迟
        setTimeout(() => {
          loading.value = false
        }, 500)
      } catch (error) {
        ElMessage.error('获取文档列表失败')
        loading.value = false
      }
    }
    
    // 显示上传对话框
    const showUploadDialog = () => {
      uploadForm.project_id = ''
      uploadForm.description = ''
      uploadForm.file = null
      uploadDialogVisible.value = true
    }
    
    // 显示创建文件夹对话框
    const showCreateFolderDialog = () => {
      folderForm.name = ''
      folderForm.project_id = ''
      folderForm.description = ''
      createFolderDialogVisible.value = true
    }
    
    // 处理文件选择变化
    const handleFileChange = (file) => {
      uploadForm.file = file.raw
    }
    
    // 提交上传
    const submitUpload = () => {
      uploadFormRef.value.validate(async (valid) => {
        if (valid && uploadForm.file) {
          try {
            // 实际项目中应该调用API上传文件
            // await store.dispatch('document/uploadDocument', {
            //   file: uploadForm.file,
            //   project_id: uploadForm.project_id,
            //   description: uploadForm.description,
            //   path: currentPath.value.map(folder => folder.name).join('/')
            // })
            
            // 模拟上传成功
            const project = projects.value.find(p => p.id === uploadForm.project_id)
            const newDocument = {
              id: documents.value.length + 1,
              name: uploadForm.file.name,
              type: getFileType(uploadForm.file.name),
              extension: getFileExtension(uploadForm.file.name),
              size: uploadForm.file.size,
              project_id: uploadForm.project_id,
              project_name: project ? project.name : '',
              path: currentPath.value.length > 0 ? `/${currentPath.value.map(folder => folder.name).join('/')}` : '/',
              created_by: '当前用户',
              created_at: new Date().toLocaleString(),
              updated_at: new Date().toLocaleString(),
              url: URL.createObjectURL(uploadForm.file),
              description: uploadForm.description
            }
            
            documents.value.push(newDocument)
            ElMessage.success('文档上传成功')
            uploadDialogVisible.value = false
          } catch (error) {
            ElMessage.error('文档上传失败')
          }
        }
      })
    }
    
    // 提交创建文件夹
    const submitCreateFolder = () => {
      folderFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            // 实际项目中应该调用API创建文件夹
            // await store.dispatch('document/createFolder', {
            //   name: folderForm.name,
            //   project_id: folderForm.project_id,
            //   description: folderForm.description,
            //   path: currentPath.value.map(folder => folder.name).join('/')
            // })
            
            // 模拟创建成功
            const project = projects.value.find(p => p.id === folderForm.project_id)
            const newFolder = {
              id: documents.value.length + 1,
              name: folderForm.name,
              type: 'folder',
              project_id: folderForm.project_id,
              project_name: project ? project.name : '',
              path: currentPath.value.length > 0 ? `/${currentPath.value.map(folder => folder.name).join('/')}` : '/',
              created_by: '当前用户',
              created_at: new Date().toLocaleString(),
              updated_at: new Date().toLocaleString(),
              description: folderForm.description
            }
            
            documents.value.push(newFolder)
            ElMessage.success('文件夹创建成功')
            createFolderDialogVisible.value = false
          } catch (error) {
            ElMessage.error('文件夹创建失败')
          }
        }
      })
    }
    
    // 下载文档
    const downloadDocument = (document) => {
      // 实际项目中应该调用API下载文件
      // window.location.href = document.download_url
      
      // 模拟下载
      ElMessage.success(`开始下载文件：${document.name}`)
    }
    
    // 预览文档
    const showPreviewDocument = (document) => {
      previewDocument.value = document
      previewDialogVisible.value = true
    }
    
    // 删除文档
    const deleteDocument = (document) => {
      ElMessageBox.confirm(
        `确定要删除${document.type === 'folder' ? '文件夹' : '文档'} "${document.name}"吗？${document.type === 'folder' ? '文件夹内的所有文件也将被删除！' : ''}`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        // 实际项目中应该调用API删除文档
        // store.dispatch('document/deleteDocument', document.id)
        
        // 模拟删除
        const index = documents.value.findIndex(d => d.id === document.id)
        if (index !== -1) {
          documents.value.splice(index, 1)
        }
        ElMessage.success(`${document.type === 'folder' ? '文件夹' : '文档'}删除成功`)
      }).catch(() => {
        // 取消删除
      })
    }
    
    // 重命名文档
    const renameDocument = (document) => {
      ElMessageBox.prompt(
        '请输入新名称',
        '重命名',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue: document.name,
          inputValidator: (value) => {
            if (!value) {
              return '名称不能为空'
            }
            return true
          }
        }
      ).then(({ value }) => {
        // 实际项目中应该调用API重命名文档
        // store.dispatch('document/renameDocument', { id: document.id, name: value })
        
        // 模拟重命名
        const index = documents.value.findIndex(d => d.id === document.id)
        if (index !== -1) {
          documents.value[index].name = value
          documents.value[index].updated_at = new Date().toLocaleString()
        }
        ElMessage.success('重命名成功')
      }).catch(() => {
        // 取消重命名
      })
    }
    
    // 显示文档属性
    const showDocumentProperties = (document) => {
      let content = `
        <div style="text-align: left;">
          <p><strong>名称：</strong>${document.name}</p>
          <p><strong>类型：</strong>${document.type === 'folder' ? '文件夹' : getFileTypeLabel(document.type)}</p>
          ${document.type !== 'folder' ? `<p><strong>大小：</strong>${formatFileSize(document.size)}</p>` : ''}
          <p><strong>所属项目：</strong>${document.project_name}</p>
          <p><strong>创建者：</strong>${document.created_by}</p>
          <p><strong>创建时间：</strong>${document.created_at}</p>
          <p><strong>更新时间：</strong>${document.updated_at}</p>
          ${document.description ? `<p><strong>描述：</strong>${document.description}</p>` : ''}
        </div>
      `
      
      ElMessageBox.alert(
        content,
        '文档属性',
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定'
        }
      )
    }
    
    // 打开文件夹
    const openFolder = (folder) => {
      currentPath.value.push(folder)
      contextMenuVisible.value = false
    }
    
    // 处理行点击事件
    const handleRowClick = (row) => {
      if (row.type === 'folder') {
        openFolder(row)
      } else {
        showPreviewDocument(row)
      }
    }
    
    // 处理右键菜单事件
    const handleContextMenu = (row, column, event) => {
      event.preventDefault()
      selectedDocument.value = row
      contextMenuVisible.value = true
      contextMenuStyle.value = {
        top: `${event.clientY}px`,
        left: `${event.clientX}px`
      }
    }
    
    // 处理页码变化
    const handlePageChange = (page) => {
      currentPage.value = page
    }
    
    // 处理搜索清除
    const handleSearchClear = () => {
      searchQuery.value = ''
    }
    
    // 获取路径字符串
    const getPathUpTo = (index) => {
      return currentPath.value.slice(0, index + 1).map(folder => folder.name).join('/')
    }
    
    // 格式化文件大小
    const formatFileSize = (size) => {
      if (size < 1024) {
        return size + ' B'
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(2) + ' KB'
      } else if (size < 1024 * 1024 * 1024) {
        return (size / (1024 * 1024)).toFixed(2) + ' MB'
      } else {
        return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB'
      }
    }
    
    // 获取文件类型
    const getFileType = (filename) => {
      const extension = getFileExtension(filename).toLowerCase()
      
      if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg'].includes(extension)) {
        return 'image'
      } else if (['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv'].includes(extension)) {
        return 'video'
      } else if (['doc', 'docx', 'pdf', 'txt', 'xls', 'xlsx', 'ppt', 'pptx'].includes(extension)) {
        return 'document'
      } else {
        return 'other'
      }
    }
    
    // 获取文件类型标签
    const getFileTypeLabel = (type) => {
      const typeMap = {
        'document': '文档',
        'image': '图片',
        'video': '视频',
        'other': '其他'
      }
      return typeMap[type] || '未知'
    }
    
    // 获取文件扩展名
    const getFileExtension = (filename) => {
      return filename.split('.').pop() || ''
    }
    
    // 判断是否为图片文件
    const isImageFile = (filename) => {
      const extension = getFileExtension(filename).toLowerCase()
      return ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg'].includes(extension)
    }
    
    // 判断是否为视频文件
    const isVideoFile = (filename) => {
      const extension = getFileExtension(filename).toLowerCase()
      return ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv'].includes(extension)
    }
    
    // 判断是否为PDF文件
    const isPdfFile = (filename) => {
      const extension = getFileExtension(filename).toLowerCase()
      return extension === 'pdf'
    }
    
    // 获取视频MIME类型
    const getVideoType = (filename) => {
      const extension = getFileExtension(filename).toLowerCase()
      const typeMap = {
        'mp4': 'video/mp4',
        'avi': 'video/x-msvideo',
        'mov': 'video/quicktime',
        'wmv': 'video/x-ms-wmv',
        'flv': 'video/x-flv',
        'mkv': 'video/x-matroska'
      }
      return typeMap[extension] || ''
    }
    
    // 点击其他地方关闭右键菜单
    const handleClickOutside = () => {
      contextMenuVisible.value = false
    }
    
    onMounted(() => {
      fetchDocuments()
      document.addEventListener('click', handleClickOutside)
    })
    
    onBeforeUnmount(() => {
      document.removeEventListener('click', handleClickOutside)
    })
    
    return {
      loading,
      searchQuery,
      filterProject,
      filterType,
      currentPage,
      pageSize,
      projects,
      documents,
      filteredDocuments,
      totalDocuments,
      uploadDialogVisible,
      createFolderDialogVisible,
      previewDialogVisible,
      previewDocument,
      uploadForm,
      folderForm,
      uploadFormRef,
      folderFormRef,
      uploadRules,
      folderRules,
      currentPath,
      contextMenuVisible,
      contextMenuStyle,
      selectedDocument,
      showUploadDialog,
      showCreateFolderDialog,
      handleFileChange,
      submitUpload,
      submitCreateFolder,
      downloadDocument,
      showPreviewDocument,
      deleteDocument,
      renameDocument,
      showDocumentProperties,
      openFolder,
      handleRowClick,
      handleContextMenu,
      handlePageChange,
      handleSearchClear,
      getPathUpTo,
      formatFileSize,
      isImageFile,
      isVideoFile,
      isPdfFile,
      getVideoType
    }
  }
}
</script>

<style scoped>
.documents-container {
  padding: 20px;
}

.documents-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
}

.documents-filters {
  display: flex;
  margin-bottom: 20px;
}

.breadcrumb-container {
  margin-bottom: 20px;
}

.document-name {
  display: flex;
  align-items: center;
}

.document-icon {
  margin-right: 8px;
  font-size: 18px;
}

.folder-icon {
  color: #E6A23C;
}

.document-icon {
  color: #409EFF;
}

.image-icon {
  color: #67C23A;
}

.video-icon {
  color: #F56C6C;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.image-preview img {
  max-width: 100%;
  max-height: 70vh;
}

.video-preview video {
  max-width: 100%;
  max-height: 70vh;
}

.pdf-preview {
  width: 100%;
}

.document-preview {
  text-align: center;
  padding: 30px;
}

.context-menu {
  position: fixed;
  background: white;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 3000;
}

.context-menu ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.context-menu li {
  padding: 8px 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.context-menu li:hover {
  background-color: #f5f7fa;
}

.context-menu li i {
  margin-right: 8px;
}
</style>